﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Encoder = System.Drawing.Imaging.Encoder;

namespace BenaGo.Helper
{
    public class BeanGoCompressionHelper
    {
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        /// <summary>
        /// 通过质量压缩图片
        /// </summary>
        /// <param name="iSource">传入的Bitmap对象</param>
        /// <param name="cStream">压缩后的Stream对象</param>
        /// <param name="level">压缩等级，0到100，0 最差质量，100 最佳</param>
        public static void Compress(Bitmap iSource, Stream cStream, long level)
        {
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;

            // Get an ImageCodecInfo object that represents the JPEG codec.
            myImageCodecInfo = GetEncoderInfo("image/jpeg");

            // Create an Encoder object based on the GUID

            // for the Quality parameter category.
            myEncoder = Encoder.Quality;

            // 创建一个 EncoderParameters 对象.
            // 一个 EncoderParameters 对象有一组EncoderParameter对象
            // 在下面的代码中，EncoderParameters数组中只有一个EncoderParameter对象
            myEncoderParameters = new EncoderParameters(1);

            // 用给定的Level值压缩图片
            myEncoderParameter = new EncoderParameter(myEncoder, level);
            myEncoderParameters.Param[0] = myEncoderParameter;
            iSource.Save(cStream, myImageCodecInfo, myEncoderParameters);
        }

        /// <summary>
        /// 通过递归的方式，以起点level 和 终点 图像字节长度length 对图像进行压缩 
        /// </summary>
        /// <param name="srcBitMap">传入的Bitmap对象</param>
        /// <param name="destFile">压缩后的图片保存路径</param>
        /// <param name="level">压缩等级，0到100，0 最差质量，100 最佳</param>
        /// <param name="length">终点长度 单位字节; 1024字节 = 1kb ; 1024kb = 1MB </param>
        public static void Compress(Bitmap srcBitMap, string destFile, long level, long length)
        {
            Stream s = new FileStream(destFile, FileMode.Create);
            Compress(srcBitMap, s, level);
            if (s.Length > length)
            {
                s.Close();
                if (File.Exists(destFile))
                {
                    File.Delete(destFile);
                }
                Compress(srcBitMap, destFile, --level, length);
            }
            s.Close();
            srcBitMap.Dispose();
        }

    }
}
